package com.itcast.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.itcast.order.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;



    @GetMapping("/buy/{id}")
    @SentinelResource(blockHandler = "orderBlockHandler", fallback = "orderFallback")
    public Product findById(@PathVariable Long id){
        if (id != 1) {
            throw new RuntimeException();
        }
        Product product = restTemplate.getForObject("http://localhost:9001/product/" + id, Product.class);
        return product;
    }

    /**
     * 定义降级逻辑
     * 1.熔断降级方法
     * 2.抛出异常降级方法
     */
    public Product orderBlockHandler(Long id) {
        Product product = new Product();
        product.setProductName("触发熔断降级方法");
        return  product;
    }
    public Product orderFallback(Long id) {
        Product product = new Product();
        product.setProductName("抛出异常降级方法");
        return  product;
    }
}
